import config from '../config.js';
let header;
const http = (params) => {
  let url = config.apiHost + params.url;
  return new Promise((resole, reject) => {
    wx.getStorage({
      key: 'token',
      success: function(res) {
        url += `?sessionKey=${res.data}`
        header={
          "Content-Type": "application/json"
        }
      },
      complete(){
        wx.request({
          url,
          data: params.data,
          header: params.header || header,
          method: params.method || 'GET',
          dataType: params.dataType,//返回的数据格式,默认为JSON，特殊格式可以在调用的时候传入参数16      
          responseType: params.responseType,//响应的数据类型
          success(res) {
            switch (res.statusCode){
              case 200:
                switch (res.data.statusCode){
                  case "401":
                    let pages = getCurrentPages();
                    let currentRouter;
                    if (pages.length){
                      currentRouter = pages[pages.length - 1].route;
                    }
                    if (currentRouter !=='pages/login/login'){
                      wx.redirectTo({
                        url: `/pages/login/login`,
                      })
                    }
                  break;
                  case "200":
                  case "300":
                    resole(res.data);
                  break;
                  default:
                    wx.showToast({
                      title: res.data.desc,
                      icon: 'none',
                      duration: 2000
                    })
                    reject(res.data);
                  break
                }
              break;
              default:
                console.log(res.data);
                reject(res.data);
              break;
            }
          },
          fail: function (e) {
            console.log(e);
            reject(e);
          }
        })
      }
    })
  
  })
}
const httpFormData = (params) => {
  let url = config.apiHost + params.url;
  return new Promise((resole, reject) => {
    wx.getStorage({
      key: 'token',
      success: function (res) {
        url += `?sessionKey=${res.data}`
        header = {
          "Content-Type": "multipart/form-data"
        }
      },
      complete() {
        wx.uploadFile({
          url,
          filePath: params.filePath,
          name: 'file',
          formData: params.formData,
          header,
          success(res) {  
            resole(res.data)
          },
          fail(error){
            reject(e);
          }})
      }
    })
  })
}
module.exports = {
   http,
  httpFormData,
}

